import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    udpMessages: [], // 存储 UDP 消息
    sendMessages: [], // 存储发送的消息
    serverIp: '192.168.0.169',
    sendport: 9091,
  },
  mutations: {
    // 接收到的数据会替换 udpMessages 中的所有内容，仅保留最新的数据
    jsonmsg(state, data) {
      state.udpMessages = [data]; // 清空数组并添加最新的数据
    },

    // 发送的数据会替换 sendMessages 中的所有内容，仅保留最新的数据
    sendmsg(state, payload) {
      state.sendMessages = [payload]; // 清空数组并添加最新的数据
    },

    setServerIp(state, ip) {
      state.serverIp = ip;
    },

    setSendport(state, port) {
      state.sendport = port;
    },
  },
  actions: {
    async updateUdpMessages({ commit }, messages) {
      // 异步提交 UDP 消息
      await new Promise(resolve => {
        setTimeout(() => {
          commit('setUdpMessages', messages);
          resolve();
        }, 0);
      });
    },

    async updateSendMessages({ commit }, payload) {
      // 异步提交发送消息
      await new Promise(resolve => {
        setTimeout(() => {
          commit('setSendMessages', payload);
          resolve();
        }, 0);
      });
    },

    async updateServerIp({ commit }, ip) {
      commit('setServerIp', ip);
    },

    async updateSendport({ commit }, port) {
      commit('setSendport', port);
    },
  },
  getters: {
    // 获取存储的 UDP 消息
    getUdpMessages(state) {
      return state.udpMessages;
    },
  },
});

export default store;
